<?php
namespace Api\Controller;

class RefundController extends WXController {
    public $tbName = 'Order';

    /**
     *  微信回调
     */
    public function notify(){
        try{
            $xml = file_get_contents('php://input');
            $result = (array)simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
            //debug($result,'refund.txt');
            $res = $result['return_code'];
            if($res == 'SUCCESS'){
                $decryptMsg = $this->refund_decrypt($result['req_info'],C('Config.key'));
                debug($decryptMsg,'refund.txt');
                //回调处理
                $msg = (array)simplexml_load_string($decryptMsg, 'SimpleXMLElement', LIBXML_NOCDATA);
                debug($msg,'refund.txt');
                $this->handle($msg);
                /*返回*/
                $res = array(
                    'return_code' => 'SUCCESS',
                    'return_msg' => 'OK',
                );
                header('Content-Type:text/xml; charset=utf-8');
                exit($this->arrayToXml($res));
            }
        }catch(\Exception $e){
            debug($e->getmessage());
        }
    }

    protected function handle($data,$num = 1){
        try{
            if($num < 4){
                if($data['refund_status'] === 'SUCCESS'){
                    //判断订单状态是否已修改
                    $Order = M('order');
                    $info = $Order->where(array('wx_num' => $data['transaction_id']))->find();
                    if($info && $info['status'] != 11){
                        $flag  = $Order->where('wx_num',$data['transaction_id'])->save(array('status' => 11,'tstamp'=>time()));
                        if(!$flag){
                            debug('修改订单退款状态失败');
                            debug($Order->_sql());
                            ++$num;
                            return $this->handle($data,$num);
                        }else{
                            debug('修改订单退款状态在第'.$num.'次成功');
                        }
                    }
                }
            }else{
                debug('修改订单退款状态超过3次');
            }
        }catch(\Exception $e){
            debug($e->getmessage());
        }
    }

    /**
     * 微信退款-回调解密
     *
     */
    public function refund_decrypt($str, $key) {  
        $key = md5($key);
        $str = base64_decode($str);  
        $str = @mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $str, MCRYPT_MODE_ECB);  
        $block = @mcrypt_get_block_size('rijndael_128', 'ecb');  
        $pad = ord($str[($len = strlen($str)) - 1]);  
        $len = strlen($str);  
        $pad = ord($str[$len - 1]);  
        return substr($str, 0, strlen($str) - $pad);  
    }
}

?>